/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.max.oti.system.bean;

import com.max.oti.system.model.Practice;
import com.max.oti.system.model.User;
import com.max.oti.system.service.interfac.IPracticeService;
import com.max.oti.system.service.interfac.IUserService;
import com.max.oti.system.util.Clazz;
import com.max.oti.system.util.FacesUtil;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import org.omnifaces.util.Faces;

/**
 *
 * @author max
 */
@ManagedBean
@ViewScoped
public class LoginBean implements Serializable {

    private Integer idSelectedRadio = 1;
    private User user = new User();
    private String typeUser = "Comisión";
    public boolean noAlumn = true;
    ////////////////////////////////////////////////////
    @ManagedProperty("#{userService}")
    IUserService userService;
    @ManagedProperty("#{clazz}")
    Clazz clazz;
    @ManagedProperty("#{practiceService}")
    IPracticeService practiceService;
    @ManagedProperty("#{indexLoginBean}")
    IndexLoginBean indexLoginBean;
    

    @PostConstruct
    public void confirmData() {
        try {

            List<Integer> listConfirm = userService.listHQL("select s.id from State s", 0, 1);

            if (listConfirm.isEmpty()) {
                System.out.println("No existen usuarios");
                User userNew = new User();
                /////////////CREA UN ESTADO////////////
                userNew.setAccessList(null);
                userNew.setDniPerson("00000000");
                userNew.setIdState(clazz.STATE(Clazz.STATE.Name.ACTIVO, Clazz.STATE.Entity.USER));
                userNew.setIdTypeComission(clazz.TYPE_COMISSION(Clazz._TYPECOMISSION.SPPP));
                userNew.setIdTypeUser(clazz._TYPE_USER(Clazz._TYPEUSER.ADMINISTRADOR));
                userNew.setNick("sppp");
                userNew.setPassword("sppp");

                System.out.println(userService.save(userNew));
            } else {
                System.out.println("Existe al menos un usuario");
            }
        } catch (Exception ex) {
            System.out.println(ex.getCause());
            Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void logginProcess() {
        if (typeUser.equals("Comisión")) {

            try {
                List<User> listUser = userService.listHQL("FROM User u WHERE u.nick='" + user.getNick() + "' "
                        + "AND u.password='" + user.getPassword() + "'");

                if (listUser.size() > 0) {
                    User users = listUser.get(0);
                    if (users.getIdState().getName().equals(Clazz.STATE.Name.ACTIVO)) {
                        users.getIdTypeComission();
                        users.getIdTypeUser();
                        users.getIdState();
                        Faces.getSession().setAttribute("usuario", users);

                        if (users.getIdTypeComission().getName().equals(Clazz._TYPECOMISSION.SGT)) {//COMISION DE GRADOS Y TITULOS
                            Faces.redirect("./pages/sgt/index.jsf");
                        } else if (users.getIdTypeComission().getName().equals(Clazz._TYPECOMISSION.SPPP)) {//COMISION DE SPPP
                            Faces.redirect("./pages/sppp/index.jsf");
                            indexLoginBean.generateMenuComission();
                        } else if (users.getIdTypeComission().getName().equals(Clazz._TYPECOMISSION.ADMIN)) {//ADMINISTRADOR DEL SISTEMA
                            Faces.redirect("./pages/admin/index.jsf");
                        }
                    } else {
                        FacesUtil.addMessage("Usuario Desactivado", "Contacte con su comisión", FacesMessage.SEVERITY_ERROR);
                    }
                } else {
                    FacesUtil.addMessage("Datos Incorrector", null, FacesMessage.SEVERITY_WARN);
                }

            } catch (Exception ex) {
                Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
            }

        } else {

            System.out.println("AUTENTIFICANDO ALUMNO.");
            String HQL = "select pr.id as id, pr.codeAlumn as codeAlumn, pr.names as names from Practice pr where pr.codeAlumn='(code)'";
            HQL = HQL.replace("(code)", user.getNick());
            
            try {
                
                List<Practice> listPractice = practiceService.listHQL(HQL, Practice.class);
                
                if (listPractice.isEmpty()) {
                    FacesUtil.addMessage("Practicante no encontrado", null, FacesMessage.SEVERITY_WARN);
                } else {
                    User user = new User();
                    user.setId(listPractice.get(0).getId());
                    user.setDniPerson(listPractice.get(0).getNames());
                    user.setNick(listPractice.get(0).getNames());
                    
                    Faces.getSession().setAttribute("usuario", user);
                    indexLoginBean.generateMenuPractice();
                    Faces.redirect("./pages/sppp/index.jsf");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }


        }

    }

    public void changeView(){
        if( typeUser.equals("Comisión") ) {
            noAlumn = true;
        } else {
            noAlumn = false;
        }
                
    }    
    //<editor-fold defaultstate="collapsed" desc=" METODOS GETTER Y SETTER ">
    public Integer getIdSelectedRadio() {
        return idSelectedRadio;
    }

    public String getTypeUser() {
        return typeUser;
    }

    public boolean isNoAlumn() {
        return noAlumn;
    }

    public void setPracticeService(IPracticeService practiceService) {
        this.practiceService = practiceService;
    }

    public void setTypeUser(String typeUser) {
        this.typeUser = typeUser;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public IndexLoginBean getIndexLoginBean() {
        return indexLoginBean;
    }

    public void setIndexLoginBean(IndexLoginBean indexLoginBean) {
        this.indexLoginBean = indexLoginBean;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    public void setClazz(Clazz clazz) {
        this.clazz = clazz;
    }

    public void setIdSelectedRadio(Integer idSelectedRadio) {
        this.idSelectedRadio = idSelectedRadio;
    }
    //</editor-fold>
}
